import React, { useState,useEffect } from 'react';
import { LockOutlined,MobileOutlined,SafetyOutlined,MailOutlined } from '@ant-design/icons';
import { Button, Form, Input, } from 'antd';
import { useHistory } from 'react-router-dom';
import backgroundImage from '../assets/images/1.jpg';
import axios from 'axios';
import { Carousel } from 'react-responsive-carousel';
import logo1 from '../assets/images/2.jpg';
import logo2 from '../assets/images/3.jpg';
import logo3 from '../assets/images/4.jpg';
import logo4 from '../assets/images/5.jpg';
import logo5 from '../assets/images/6.jpg';
import logo6 from '../assets/images/7.jpg';

const Register = () => {
  //使用useState定义一个名为formValid的state变量，并将初始值设为false
  const [formValid, setFormValid] = useState(false);
  // const [number,setNumber] = useState('');
  const [username,setUsername] = useState('');
  const [passwd,setPasswd] = useState('');
  const [phone,setPhone] = useState('');
  const [email,setEmail] = useState('');
  const [verifyMsg,setverifyMsg] = useState('');
  const [vcode,setVcode] = useState('');
  //定义history，以便界面跳转
  const history = useHistory();
  const [form] = Form.useForm();
  // const onClick1 = () => {
  //   form.validateFields().then(() => {
  //     if (formValid) {
  //       console.log('Reigster successful');
  //       // 点击注册跳转到登录页面
  //       history.push("/login");
  //     }
  //   });
  // };

  // 添加倒计时状态变量
  const [countdown, setCountdown] = useState(0);
  // 点击发送手机验证码按钮，发送验证码
  const submitClick = () =>{
    axios.post('http://localhost:2023/auth/verifyMsg', {
      tel_number:phone,
      })
      .then((res) => {
        console.log(res);
      })
      .catch((error) => {
        console.log(error);
      });
      if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(phone)) {
        return;
      }
      setCountdown(60);
  }
  //定义phone的数值进行输入判断，并提醒手机号是否正确，rule不可删除  
  const validatePhoneNumber = (rule, value) => {
    return new Promise((resolve, reject) => {
      if (!value) {
        reject('请输入手机号!');
      } else if (!/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/.test(value)) {
        reject('手机号格式不正确!');
      } else {
        resolve();
      }
    });
  };  
  // 定义验证码，提示输入验证码，rule不可删除
  const validateCaptcha = (rule, value) => {
    return new Promise((resolve, reject) => {
      if (!value) {
        reject('请输入验证码!');
      } else {
        resolve();
      }
    });
  };
  // 定义一个禁用的按钮，手机号未输入不能点击发送验证码
  const disableButton = !phone || countdown > 0;
  // 设置定时器，进行倒计时显示
  useEffect(() => {
    if (countdown > 0) {
      const timer = setTimeout(() => {
        setCountdown(countdown - 1);
      }, 1000);
      return () => clearTimeout(timer);
    }
  }, [countdown]);

   // 轮播图
   const [currentSlide, setCurrentSlide] = useState(0);
   // 增加或减少当前幻灯片的函数
   const nextSlide = () => {
     setCurrentSlide((prevSlide) => (prevSlide === totalSlides - 1 ? 0 : prevSlide + 1));
   };
   const prevSlide = () => {
     setCurrentSlide((prevSlide) => (prevSlide === 0 ? totalSlides - 1 : prevSlide - 1));
   };
   const totalSlides = 6; // 假设有6张图片
   useEffect(() => {
     const interval = setInterval(() => {
       nextSlide();
     }, 2500);
 
     return () => {
       clearInterval(interval);
     };
   }, [currentSlide]);
 

  // 点击发送注册请求
  const onFinish = (values) => {
    console.log('Received values of form: ', values);
    setFormValid(true);
    axios.post('http://localhost:2023/auth/register', {
      username:username,
      phone:phone, 
      passwd:passwd, 
      email:email, 
      verifyMsg:verifyMsg,  //手机号验证码
      vcode:vcode,  //学信网
    })
    .then((res) => {
      console.log(res.data);
      history.push('/Login');
      // if (res.data.error){
      //   message.error(res.data.error);
      // }else{
      //     saveUser(res.data);
      //     message.success('注册成功');
      //     history.push('/Login');
      // }
    })
    .catch((error) => {
      
    });
  };

  return (
    <div style={{ 
      display: 'flex', 
      justifyContent: 'center', 
      height: '97vh', 
      alignItems: 'center',
      backgroundImage: `url(${backgroundImage})`,//背景图
      backgroundSize: 'cover',
      }}>
        {/* 轮播图 */}
       <div style={{ position: 'relative', maxWidth: '600px', margin: '0 auto',marginLeft:250,borderRadius: '20px 0 0 20px',backgroundColor: 'rgba(255, 255, 255, 0)', }}>
      <Carousel
        selectedItem={currentSlide}
        onChange={(index) => setCurrentSlide(index)}
        showThumbs={false}
        autoPlay={false}
        infiniteLoop={true}
        showArrows={false}
        showStatus={false}
        showIndicators={false}
      >
          <img src={logo1} alt="Image 1" style={{ width: 650, height: 518,borderRadius: '20px 0 0 20px'  }} />
          <img src={logo2} alt="Image 2" style={{ width: 650, height: 518,borderRadius: '20px 0 0 20px'  }} />
          <img src={logo3} alt="Image 3" style={{ width: 650, height: 518,borderRadius: '20px 0 0 20px' }} />
          <img src={logo4} alt="Image 4" style={{ width: 650, height: 518,borderRadius: '20px 0 0 20px'}} />
          <img src={logo5} alt="Image 5" style={{ width: 650, height: 518,borderRadius: '20px 0 0 20px'}} />
          <img src={logo6} alt="Image 6" style={{ width: 650, height: 518,borderRadius: '20px 0 0 20px'}} />    
      </Carousel>
      <div style={{ position: 'absolute', top: '50%', transform: 'translateY(-50%)', left: -15 }}>
        <Button onClick={prevSlide} type="link" style={{color: '#55CA92',fontSize:30}}>{"<"}</Button>
      </div>
      <div style={{ position: 'absolute', top: '50%', transform: 'translateY(-50%)', right: -15}}>
        <Button onClick={nextSlide} type="link" style={{color: '#55CA92',fontSize:30}}>{">"}</Button>
      </div>
    </div>
      <div style={{ 
        border: '1px solid #BEBEBE',
        width: 300,
        padding: 20,
        borderRadius:'0 10px 10px 0',
        boxShadow: '0 2px 4px rgba(0, 0, 0, 0.5)',
        marginRight:260,
        }}>
          {/*注册标题  */}
        <h1 style={{ 
          textAlign: 'center' 
          }}>
            注册
        </h1>
        <Form
          name="normal_register"
          className="register-form"
          initialValues={{
            remember: true,
          }}
          onFinish={onFinish}
        >
          {/* 手机号 */}
          <Form.Item
            name="phone"
            rules={[
              {
                required: true,
                validator: validatePhoneNumber,
              },
            ]}
            value={phone}
            onChange = {(e) => setPhone(e.target.value)}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <MobileOutlined className="icon" style={{ color: '#55CA92' }} />
                <Input
                  placeholder="手机号"
                  className="input"
                  style={{
                    width: 250,
                    marginLeft: 20,
                    backgroundColor: 'rgba(255, 255, 255, 0.3)',
                  }}
                />
              </div>
            </Form.Item>
            {/* 验证码 */}
            <Form.Item
              name="captcha"
              rules={[
                {
                  required: true,
                  validator: validateCaptcha,
                },
              ]}
              value={verifyMsg}
              onChange = {(e) => setverifyMsg(e.target.value)}
            >
              <div style={{ display: 'flex', alignItems: 'center' }}>
                <SafetyOutlined className="icon" style={{ color: '#55CA92' }} />
                <Input
                  type="text"
                  placeholder="验证码"
                  className="input"
                  style={{
                    width: 150,
                    marginLeft: 20,
                    backgroundColor: 'rgba(255, 255, 255, 0.3)',
                  }}
                />
                {/* 发送验证码按钮 */}
                <Button
                  style={{
                    borderRadius: 7,
                    color: 'white',
                    backgroundColor: '#55CA92',
                    marginRight: 10,
                  }}
                  onClick={submitClick}
                  disabled={disableButton}
                >
                  {countdown > 0 ? `${countdown}秒后重发` : '发送验证码'}
                </Button>
              </div>
            </Form.Item>
          {/* 密码 */}
          <Form.Item 
            name="password"
            rules={[
              {
                required: true,
                message: '请输入密码!',
              },
            ]}
            value={passwd}
            onChange = {(e) => setPasswd(e.target.value)}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center' 
              }}
            >
              <LockOutlined className="icon" style={{ color: '#55CA92' }} />
              <Input 
              type="password" 
              placeholder="密码" 
              className="input" 
              style={{ 
                width: 250, 
                marginLeft: 20,
                backgroundColor: 'rgba(255, 255, 255, 0.3)' 
              }} 
            />
            </div>
          </Form.Item>
          {/* 再次输入密码 */}
          <Form.Item 
          name="confirmPassword"
          dependencies={['password']}
          rules={[
            {
              required: true,
              message: '请再次输入密码!',
            },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('密码输入不一致!'));
              },
            }),
            ]}
            value={passwd}
            onChange = {(e) => setPasswd(e.target.value)}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center' 
             }}
            >
              <LockOutlined className="icon" style={{ color: '#55CA92' }} />
              <Input 
              type="password"
              placeholder="再次输入密码" 
              className="input"
              style={{ 
                width: 250, 
                marginLeft: 20,
                backgroundColor: 'rgba(255, 255, 255, 0.3)' 
              }} 
              />
            </div>
          </Form.Item>
            {/* 邮箱 */}
          <Form.Item
            name="email"
            rules={[
              {
                required: true,
                message: '请输入邮箱!',
              },
            ]}
            value={email}
            onChange = {(e) => setEmail(e.target.value)}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center' 
              }}
            >
              <MailOutlined className="icon" style={{ color: '#55CA92' }} />
              <Input 
              type="email" 
              placeholder="邮箱" 
              className="input" 
              style={{ 
                width: 250, 
                marginLeft: 20,
                backgroundColor: 'rgba(255, 255, 255, 0.3)' 
              }} 
              />
            </div>
          </Form.Item>
          {/* 学信网验证码 */}
          <Form.Item
            name="captcha"
            rules={[
              {
                required: true,
                message: '请输入学信网验证码!',
              },
            ]}
            value={vcode}
            onChange = {(e) => setVcode(e.target.value)}
          >
            <div style={{ 
              display: 'flex', 
              alignItems: 'center' 
              }}>
              <SafetyOutlined className="icon" style={{ color: '#55CA92' }} />
              <Input 
              type="text" 
              placeholder="学信网验证码" 
              className="input" 
              style={{ 
                width: 250, 
                marginLeft: 20,
                backgroundColor: 'rgba(255, 255, 255, 0.3)' 
              }} 
              />
            </div>
          </Form.Item>
          {/* 注册按钮 */}
          <Form.Item>
            <div 
            className="button-container" 
            style={{ 
              display: 'flex', 
              justifyContent: 'center' 
              }}>
              <Button 
              type="text" 
              htmlType="submit" 
              className="login-form-button" 
              style={{ 
                width: 200, 
                backgroundColor: '#55CA92', 
                color: 'white', 
                textAlign: 'center' 
                }}
                //onClick={onClick1}
                //form={form}
                >
                注册
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
};

export default Register;